<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006-2016 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: wangshuai <fisher@chinaluohong.com>
// +----------------------------------------------------------------------

use think\Loader;

//七牛云存储
Loader::import('qiniu_sdk.autoload', VENDOR_PATH, '.php');

use Qiniu\Auth;  // 引入鉴权类
use Qiniu\Storage\UploadManager;   // 引入上传类

use think\File;
use think\Config;
use think\Session;
use think\Db;

//判断是否登录后台
function admin_status()
{
    $admin_info = Session::get('admin_info');
    if(empty($admin_info)){
        return false;
    }else{
        return true;
    }
}

//获取ip地址
function getIP(){
    if (getenv("HTTP_CLIENT_IP"))
        $ip = getenv("HTTP_CLIENT_IP");
    else if(getenv("HTTP_X_FORWARDED_FOR"))
        $ip = getenv("HTTP_X_FORWARDED_FOR");
    else if(getenv("REMOTE_ADDR"))
        $ip = getenv("REMOTE_ADDR");
    else $ip = "Unknow";
    return $ip;
}


// 根据ip获取地址
function get_address($ip){
    $result = json_decode(file_get_contents('http://int.dpool.sina.com.cn/iplookup/iplookup.php?ip='.$ip.'&format=json'));
    $province = isset($result->province) ? $result->province : '';
    $city = isset($result->city) ? $result->city : '';
    return $province.$city;
}


//过滤敏感字符
function deletehtml($str) {
    $str = trim($str); //清除字符串两边的空格
    $str = strip_tags($str); //利用php自带的函数清除html格式
    // $str = preg_replace("/\t/", "", $str); //使用正则表达式匹配需要替换的内容，如：空格，换行，并将替换为空。
    $str = preg_replace("/\r\n/", "", $str);
    $str = preg_replace("/\r/", "", $str);
    $str = preg_replace("/\n/", "", $str);
    $str = preg_replace("/ /", "", $str);
    $str = preg_replace("/  /", "", $str);  //匹配html中的空格
    $str = str_replace("&nbsp;", "", $str);
    $str = str_replace("&middot;", "", $str);
    $str = str_replace("&rdquo;", "", $str);
    $str = str_replace("&ldquo;", "", $str);
    return trim($str); //返回字符串
}

// 使用curl模拟请求
function http_curl($url, $method='GET', $data='',$type=''){
    $curl = curl_init(); // 启动一个CURL会话
    curl_setopt($curl, CURLOPT_URL, $url); // 要访问的地址
    curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false); // 对认证证书来源的检查
    curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false); // 从证书中检查SSL加密算法是否存在
    curl_setopt($curl, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']); // 模拟用户使用的浏览器
    curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 1); // 使用自动跳转
    curl_setopt($curl, CURLOPT_AUTOREFERER, 1); // 自动设置Referer
    if($method=='POST'){
        curl_setopt($curl, CURLOPT_POST, 1); // 发送一个常规的Post请求
        if ($data != ''){
            curl_setopt($curl, CURLOPT_POSTFIELDS, $data); // Post提交的数据包
        }
    }
    if($type=='JSON'){
        $header= array('Content-Type: application/json');
        curl_setopt($curl, CURLOPT_HTTPHEADER, $header);
    }
    curl_setopt($curl, CURLOPT_TIMEOUT, 30); // 设置超时限制防止死循环
    curl_setopt($curl, CURLOPT_HEADER, 0); // 显示返回的Header区域内容
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); // 获取的信息以文件流的形式返回
    $tmpInfo = curl_exec($curl); // 执行操作
    curl_close($curl); // 关闭CURL会话
    return $tmpInfo; // 返回数据
}

//object转array
function object2array($object) {
    if (is_object($object)) {
        foreach ($object as $key => $value) {
            $array[$key] = $value;
        }
    } else {
        $array = $object;
    }
    return $array;
}

//$file文件$type文件类型$size最大上传
function upload_file($file,$type,$size,$position='/uploads/othors'){
    // 移动到框架应用根目录/public/uploads/ 目录下
//    $info = $file->validate(['size'=>$size,'ext'=>$type])->move($position);
    $position_file = ROOT_PATH.'/public'.$position;
    $info = $file->validate(['size'=>$size,'ext'=>$type])->rule('uniqid')->move($position_file);
    if($info){
        Config::load(APP_PATH.'other.php');
        $qiniu_config = Config::get('oss_qiniu');//获取七牛云配置
       if($qiniu_config['qiniu_status']){//开启了七牛云
           $file_info = $info->getInfo();
           $qiniu_status = qiniu_file($position.'/'.$info->getSaveName(),$file_info,$qiniu_config);
           if(!$qiniu_status){
               return $position.'/'.$info->getSaveName();
           }else{
               return $qiniu_status;
           }
       }
        // 成功上传后 获取上传信息
        // 输出 jpg
        //echo $info->getExtension();
        // 输出 20160820/42a79759f284b767dfcb2a0197904287.jpg
        //return $info->getSaveName();
        //输出 42a79759f284b767dfcb2a0197904287.jpg
        return $position.'/'.$info->getSaveName();
    }else{
        //return false;
        // 上传失败获取错误信息
        echo $file->getError();
        die();
    }

}

//$file_name文件名称$filepath文件路径$bucket七牛云存储bucket名称
function qiniu_file($file_name,$filepath,$qiniu_config){
    if(empty($qiniu_config['qiniu_accessKey'])||empty($qiniu_config['qiniu_secretKey'])||empty($qiniu_config['qiniu_bucket'])) return false;
    $filepath = $filepath['tmp_name'];
    $qiniu = new Auth($qiniu_config['qiniu_accessKey'], $qiniu_config['qiniu_secretKey']); // 构建鉴权对象
    $token = $qiniu->uploadToken($qiniu_config['qiniu_bucket']);
    $uploadMgr = new UploadManager();
    list($ret, $err) = $uploadMgr->putFile($token, $file_name, $filepath);
    if($err !== null) {
        return false;
    }else{
        return $qiniu_config['qiniu_url'].$ret['key'];
    }
}

//获取验证码(通过GD库)$code圖片驗證碼名稱
function getCode($num,$w,$h,$code_name) {
    $code = "";
    for ($i = 0;$i < $num; $i++){
        $code .= rand(0, 9);
    }
    //4位验证码也可以用rand(1000,9999)直接生成
    //将生成的验证码写入session，备验证时用
    Session::set($code_name,$code);
    //创建图片，定义颜色值
    header("Content-type: image/PNG");
    $im = imagecreate($w, $h);
    $black = imagecolorallocate($im, 0, 0, 0);
    $gray = imagecolorallocate($im, 200, 200, 200);
    $bgcolor = imagecolorallocate($im, 255, 255, 255);
    //填充背景
    imagefill($im, 0, 0, $gray);
    //画边框
    imagerectangle($im, 0, 0, $w-1, $h-1, $black);
    //随机绘制两条虚线，起干扰作用
    $style = array ($black,$black,$black,$black,$black, $gray,$gray,$gray,$gray,$gray);
    imagesetstyle($im, $style);
    $y1 = rand(0, $h);
    $y2 = rand(0, $h);
    $y3 = rand(0, $h);
    $y4 = rand(0, $h);
    imageline($im, 0, $y1, $w, $y3, IMG_COLOR_STYLED);
    imageline($im, 0, $y2, $w, $y4, IMG_COLOR_STYLED);
    //在画布上随机生成大量黑点，起干扰作用;
    for ($i = 0; $i < 80; $i++) {
        imagesetpixel($im, rand(0, $w), rand(0, $h), $black);
    }
    //将数字随机显示在画布上,字符的水平间距和位置都按一定波动范围随机生成
    $strx = rand(3, 8);
    for ($i = 0; $i < $num; $i++) {
        $strpos = rand(1, 6);
        imagestring($im, 5, $strx, $strpos, substr($code, $i, 1), $black);
        $strx += rand(8, 12);
    }
    imagepng($im);//输出图片
    imagedestroy($im);//释放图片所占内存
}

//判断是不是手机访问
function isMobile()
{
    // 如果有HTTP_X_WAP_PROFILE则一定是移动设备
    if (isset ($_SERVER['HTTP_X_WAP_PROFILE']))
    {
        return true;
    }
    // 如果via信息含有wap则一定是移动设备,部分服务商会屏蔽该信息
    if (isset ($_SERVER['HTTP_VIA']))
    {
        // 找不到为flase,否则为true
        return stristr($_SERVER['HTTP_VIA'], "wap") ? true : false;
    }
    // 脑残法，判断手机发送的客户端标志,兼容性有待提高
    if (isset ($_SERVER['HTTP_USER_AGENT']))
    {
        $clientkeywords = array ('nokia',
            'sony',
            'ericsson',
            'mot',
            'samsung',
            'htc',
            'sgh',
            'lg',
            'sharp',
            'sie-',
            'philips',
            'panasonic',
            'alcatel',
            'lenovo',
            'iphone',
            'ipod',
            'blackberry',
            'meizu',
            'android',
            'netfront',
            'symbian',
            'ucweb',
            'windowsce',
            'palm',
            'operamini',
            'operamobi',
            'openwave',
            'nexusone',
            'cldc',
            'midp',
            'wap',
            'mobile'
        );
        // 从HTTP_USER_AGENT中查找手机浏览器的关键字
        if (preg_match("/(" . implode('|', $clientkeywords) . ")/i", strtolower($_SERVER['HTTP_USER_AGENT'])))
        {
            return true;
        }
    }
    // 协议法，因为有可能不准确，放到最后判断
    if (isset ($_SERVER['HTTP_ACCEPT']))
    {
        // 如果只支持wml并且不支持html那一定是移动设备
        // 如果支持wml和html但是wml在html之前则是移动设备
        if ((strpos($_SERVER['HTTP_ACCEPT'], 'vnd.wap.wml') !== false) && (strpos($_SERVER['HTTP_ACCEPT'], 'text/html') === false || (strpos($_SERVER['HTTP_ACCEPT'], 'vnd.wap.wml') < strpos($_SERVER['HTTP_ACCEPT'], 'text/html'))))
        {
            return true;
        }
    }
    return false;
}

//二维数组去掉重复值
function two_array_unique($arr, $key){
$tmp_arr = array();
foreach($arr as $k => $v)
{
    if(in_array($v[$key], $tmp_arr))   //搜索$v[$key]是否在$tmp_arr数组中存在，若存在返回true
    {
        unset($arr[$k]); //销毁一个变量  如果$tmp_arr中已存在相同的值就删除该值
    }
    else {
        $tmp_arr[$k] = $v[$key];  //将不同的值放在该数组中保存
    }
}
//ksort($arr); //ksort函数对数组进行排序(保留原键值key)  sort为不保留key值
return $arr;
}

//**秒/分钟前
function formatTime($value) {
    if(time() - $value < 60) {
        return (time() - $value).'秒前';
    }
    if(time() - $value > 60 && time() - $value < 3600) {
        return ceil((time() - $value)/60).'分钟前';
    }
    if(time() - $value > 3600 && time() - $value < 86400) {
        return ceil((time() - $value)/3600).'小时前';
    }
    if(time() - $value > 86400 && time() - $value < 172800) {
        return '1天前';
    }
    return date('Y-m-d H:i:s', $value);
}

//获取两个日期之前的所有日期
function prDates($start,$end){
    $dt_start = $start;
    $dt_end = $end;
    while ($dt_start<=$dt_end){
        $pr_dates[] = date('Y-m-d',$dt_start)."\n";
        $dt_start = strtotime('+1 day',$dt_start);
        if($dt_start==$end){
            break;
        }
    }
    return $pr_dates;
}

//蜘蛛抓取
function robots(){
    $useragent = addslashes(strtolower($_SERVER['HTTP_USER_AGENT']));
    if (strpos($useragent, 'googlebot')!== false){$bot = 'Google';}
    elseif (strpos($useragent,'mediapartners-google') !== false){$bot = 'Google Adsense';}
    elseif (strpos($useragent,'baiduspider') !== false){$bot = 'Baidu';}
    elseif (strpos($useragent,'sogou spider') !== false){$bot = 'Sogou';}
    elseif (strpos($useragent,'sogou web') !== false){$bot = 'Sogou web';}
    elseif (strpos($useragent,'sosospider') !== false){$bot = 'SOSO';}
    elseif (strpos($useragent,'360spider') !== false){$bot = '360Spider';}
    elseif (strpos($useragent,'haosou') !== false){$bot = 'haosou';}
    elseif (strpos($useragent,'yahoo') !== false){$bot = 'Yahoo';}
    elseif (strpos($useragent,'msn') !== false){$bot = 'MSN';}
    elseif (strpos($useragent,'msnbot') !== false){$bot = 'msnbot';}
    elseif (strpos($useragent,'sohu') !== false){$bot = 'Sohu';}
    elseif (strpos($useragent,'yodaoBot') !== false){$bot = 'Yodao';}
    elseif (strpos($useragent,'twiceler') !== false){$bot = 'Twiceler';}
    elseif (strpos($useragent,'ia_archiver') !== false){$bot = 'Alexa_';}
    elseif (strpos($useragent,'iaarchiver') !== false){$bot = 'Alexa';}
    elseif (strpos($useragent,'slurp') !== false){$bot = '雅虎';}
    elseif (strpos($useragent,'bot') !== false){$bot = $useragent;}
    if(isset($bot)){
        return array('date'=>date('Y-m-d H:i:s'),'ip'=>$_SERVER["REMOTE_ADDR"],'spider'=>$bot,'url'=>$_SERVER['SERVER_NAME'].$_SERVER["REQUEST_URI"]);
    }
}

//百度推送
function baidu_tuisong($token,$urls){
    Config::load(APP_PATH.'other.php');
    $api = 'http://data.zz.baidu.com/urls?site='.Config::get('web_url').'&token='.$token;
    $ch = curl_init();
    $options =  array(
        CURLOPT_URL => $api,
        CURLOPT_POST => true,
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_POSTFIELDS => implode("\n", $urls),
        CURLOPT_HTTPHEADER => array('Content-Type: text/plain'),
    );
    curl_setopt_array($ch, $options);
    $result = curl_exec($ch);
    return $result;
}

//跳转提醒
function web_jump($url=''){
    if(empty($url))$url = '/';
    echo " <body><script language = 'javascript' type = 'text/javascript' > ";
    echo " window.location.href = '$url' ";
    echo " </script ></body> ";
}

//获取当天是本月的第几周
function get_week(){
    $wk_day=date('w'); //今天周几
    $day=date('d'); //今天几号
    $week=array('日','一','二','三','四','五','六'); //规范化周日的表达
    $d=ceil($day/7); //计算是第几个星期几
    $str=date("Y年n月j日")." 星期".$week[$wk_day]." - 本月的第 ".$d." 个星期".$week[$wk_day];
    return $str;
}

//生成订单号
function get_order_num(){
    $order_date = date('Y-m-d');
    //订单号码主体（YYYYMMDDHHIISSNNNNNNNN）
    $order_id_main = date('YmdHis') . rand(10000000,99999999);
    //订单号码主体长度
    $order_id_len = strlen($order_id_main);
    $order_id_sum = 0;
    for($i=0; $i<$order_id_len; $i++){
        $order_id_sum += (int)(substr($order_id_main,$i,1));
    }
    //唯一订单号码（YYYYMMDDHHIISSNNNNNNNNCC）
    $order_id = $order_id_main . str_pad((100 - $order_id_sum % 100) % 100,2,'0',STR_PAD_LEFT);
    return $order_id;
}

function make_random( $length = 8 )
{
    // 密码字符集，可任意添加你需要的字符
    $chars = array('a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z','A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z','1','2','3','4','5','6','7','8','9','0');
    // 在 $chars 中随机取 $length 个数组元素键名
    $keys = array($chars,$length);
    $result = '';
    for($i = 0; $i < $length; $i++)
    {
        // 将 $length 个数组元素连接成字符串
        $result .= $chars[$keys[$i]];
    }
    return $result;
}

//按照键值把数组分类
function group_same_key($arr,$key){
    $new_arr = array();
    foreach($arr as $k=>$v ){
        $new_arr[$v[$key]][] = $v;
    }
    return $new_arr;
}

//将内容进行UNICODE编码，编码后的内容格式：\u56fe\u7247 （原始：图片）
function unicode_encode($name)
{
    $name = iconv('UTF-8', 'UCS-2', $name);
    $len = strlen($name);
    $str = '';
    for ($i = 0; $i < $len - 1; $i = $i + 2)
    {
        $c = $name[$i];
        $c2 = $name[$i + 1];
        if (ord($c) > 0)
        {    // 两个字节的文字
            $str .= '\u'.base_convert(ord($c), 10, 16).base_convert(ord($c2), 10, 16);
        }
        else
        {
            $str .= $c2;
        }
    }
    return $str;
}

// 将UNICODE编码后的内容进行解码，编码后的内容格式：\u56fe\u7247 （原始：图片）
function unicode_decode($name)
{
    // 转换编码，将Unicode编码转换成可以浏览的utf-8编码
    $pattern = '/([\w]+)|(\\\u([\w]{4}))/i';
    preg_match_all($pattern, $name, $matches);
    if (!empty($matches))
    {
        $name = '';
        for ($j = 0; $j < count($matches[0]); $j++)
        {
            $str = $matches[0][$j];
            if (strpos($str, '\\u') === 0)
            {
                $code = base_convert(substr($str, 2, 2), 16, 10);
                $code2 = base_convert(substr($str, 4), 16, 10);
                $c = chr($code).chr($code2);
                $c = iconv('UCS-2', 'UTF-8', $c);
                $name .= $c;
            }
            else
            {
                $name .= $str;
            }
        }
    }
    return $name;
}